package com.example.train_operate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.train_operate.dto.*;
import com.example.train_operate.entity.*;
import com.example.train_operate.mapper.*;
import com.example.train_operate.service.TaskService;
import com.example.train_operate.util.Result;
import com.example.train_operate.util.UserHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.example.train_operate.util.FileUrlConstants.FILE_URL;

@Service
public class TaskServiceImpl implements TaskService {

    @Resource
    private CabinetMapper cabinetMapper;

    @Resource
    private ElectricMapper electricMapper;

    @Resource
    private ExperimentMapper experimentMapper;

    @Resource
    private HostMapper hostMapper;

    @Resource
    private NetworkMapper networkMapper;

    @Resource
    private UserMapper userMapper;

    /**
     * 查询任务详情列表
     * @return
     */
    @Override
    public Result selectTaskDetailList() {
        UserDTO user = UserHolder.getUser();
        Integer userId = user.getId();
        try {
            QueryWrapper<Experiment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId)
                    .eq("is_delete", 0)
                    .orderByDesc("create_time");
            List<Experiment> experimentList = experimentMapper.selectList(queryWrapper);
            if (experimentList == null) {
                return Result.fail().message("未查询到巡检记录");
            }
            List<TaskDetailDTO> experimentDetailList = new ArrayList<>();
            Integer totalCount = 0, totalNormalCount = 0, totalAbnormalCount = 0;
            for(Experiment experiment : experimentList){
                Integer taskCount = 5, normalTaskCount = 0, abnormalTaskCount = 0;
                List<Object> list = new ArrayList();
                Integer normalCount3 = experimentMapper.selectNormalCount(experiment.getExperimentId());
                experiment.setExperimentNormalNum(normalCount3);
                experiment.setExperimentExceptionNum(6 - normalCount3);
                if(normalCount3 == 6){
                    experiment.setExperimentIsNormal(1);
                    normalTaskCount++;
                }else {
                    experiment.setExperimentId(0);
                    abnormalTaskCount++;
                }
                String url = experiment.getPhotoUrl();
                if(url != null && !url.isEmpty()){
                    String photoUrl = FILE_URL + url;
                    experiment.setPhotoUrl(photoUrl);
                }
                list.add(experiment);
                QueryWrapper<Network> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("user_id", userId)
                        .eq("is_delete", 0)
                        .eq("network_id", experiment.getPreviousTaskId());
                Network network = networkMapper.selectOne(queryWrapper1);
                Integer normalCount2 = networkMapper.selectNormalCount(network.getNetworkId());
                network.setNetworkNormalNum(normalCount2);
                network.setNetworkExceptionNum(5 - normalCount2);
                if(normalCount2 == 5){
                    network.setNetworkIsNormal(1);
                    normalTaskCount++;
                }else {
                    network.setNetworkId(0);
                    abnormalTaskCount++;
                }
                String url1 = network.getPhotoUrl();
                if(url1 != null && !url1.isEmpty()){
                    String photoUrl = FILE_URL + url1;
                    network.setPhotoUrl(photoUrl);
                }
                list.add(network);
                QueryWrapper<Host> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("user_id", userId)
                        .eq("is_delete", 0)
                        .eq("host_id", network.getPreviousTaskId());
                Host host = hostMapper.selectOne(queryWrapper2);
                Integer normalCount1 = hostMapper.selectNormalCount(host.getHostId());
                host.setHostNormalNum(normalCount1);
                host.setHostExceptionNum(5 - normalCount1);
                if(normalCount1 == 5){
                    host.setHostIsNormal(1);
                    normalTaskCount++;
                }else {
                    host.setHostId(0);
                    abnormalTaskCount++;
                }
                String url2 = host.getPhotoUrl();
                if(url2 != null && !url2.isEmpty()){
                    String photoUrl = FILE_URL + url2;
                    host.setPhotoUrl(photoUrl);
                }
                list.add(host);
                QueryWrapper<Electric> queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.eq("user_id", userId)
                        .eq("is_delete", 0)
                        .eq("electric_id", host.getPreviousTaskId());
                Electric electric = electricMapper.selectOne(queryWrapper3);
                Integer normalCount = electricMapper.selectNormalCount(electric.getElectricId());
                electric.setElectricNormalNum(normalCount);
                electric.setElectricExceptionNum(4 - normalCount);
                if(normalCount == 4){
                    electric.setElectricIsNormal(1);
                    normalTaskCount++;
                }else {
                    electric.setElectricId(0);
                    abnormalTaskCount++;
                }
                String url3 = host.getPhotoUrl();
                if(url3 != null && !url3.isEmpty()){
                    String photoUrl = FILE_URL + url3;
                    electric.setPhotoUrl(photoUrl);
                }
                list.add(electric);
                QueryWrapper<Cabinet> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.eq("user_id", userId)
                        .eq("is_delete", 0)
                        .eq("cabinet_id", electric.getPreviousTaskId());
                Cabinet cabinet = cabinetMapper.selectOne(queryWrapper4);
                Integer cabinetNormalNum = cabinetMapper.selectNormalCount(cabinet.getCabinetId());
                cabinet.setCabinetNormalNum(cabinetNormalNum);
                cabinet.setCabinetExceptionNum(6 - cabinetNormalNum);
                if (cabinetNormalNum == 6){
                    cabinet.setCabinetIsNormal(1);
                    normalTaskCount++;
                }else {
                    cabinet.setCabinetId(0);
                    abnormalTaskCount++;
                }
                String url4 = cabinet.getPhotoUrl();
                if(url4 != null && !url4.isEmpty()){
                    String photoUrl = FILE_URL + url4;
                    cabinet.setPhotoUrl(photoUrl);
                }
                list.add(cabinet);
                Collections.reverse(list);
                TaskDetailDTO taskDetailDTO = new TaskDetailDTO();
                taskDetailDTO.setTaskDetailList(list);
                taskDetailDTO.setTaskCount(taskCount);
                taskDetailDTO.setNormalTaskCount(normalTaskCount);
                taskDetailDTO.setAbnormalTaskCount(abnormalTaskCount);
                experimentDetailList.add(taskDetailDTO);
                totalCount++;
                if(abnormalTaskCount == 0){
                    totalNormalCount++;
                }else {
                    totalAbnormalCount++;
                }
            }
            InspectionRecordDTO inspectionRecordDTO = new InspectionRecordDTO();
            inspectionRecordDTO.setInspectionRecordList(experimentDetailList);
            inspectionRecordDTO.setNormalCount(totalNormalCount);
            inspectionRecordDTO.setAbnormalCount(totalAbnormalCount);
            return Result.ok(inspectionRecordDTO);
        } catch (Exception e){
            return Result.fail().message("巡检任务查询失败！");
        }
    }

    /**
     * 查询巡检任务正常数和异常数
     * @return
     */
    @Override
    public Result selectTotalCount() {
        Integer totalNormalCount = 0, totalAbnormalCount = 0;
        try{
            Integer cabinetNormalCount = cabinetMapper.selectNormalTotalCount();
            totalNormalCount += cabinetNormalCount;
            Integer cabinetAbnormalCount = cabinetMapper.selectAbnormalTotalCount();
            totalAbnormalCount += cabinetAbnormalCount;
            Integer electricNormalCount = electricMapper.selectNormalTotalCount();
            totalNormalCount += electricNormalCount;
            Integer electricAbnormalCount = electricMapper.selectAbnormalTotalCount();
            totalAbnormalCount += electricAbnormalCount;
            Integer hostNormalCount = hostMapper.selectNormalTotalCount();
            totalNormalCount += hostNormalCount;
            Integer hostAbnormalCount = hostMapper.selectAbnormalTotalCount();
            totalAbnormalCount += hostAbnormalCount;
            Integer networkNormalCount = networkMapper.selectNormalTotalCount();
            totalNormalCount += networkNormalCount;
            Integer networkAbnormalCount = networkMapper.selectAbnormalTotalCount();
            totalAbnormalCount += networkAbnormalCount;
            Integer experimentNormalCount = experimentMapper.selectNormalTotalCount();
            totalNormalCount += experimentNormalCount;
            Integer experimentAbnormalCount = experimentMapper.selectAbnormalTotalCount();
            totalAbnormalCount += experimentAbnormalCount;
            NormalAndAbnormalCountDTO normalAndAbnormalCountDTO = new NormalAndAbnormalCountDTO();
            normalAndAbnormalCountDTO.setTotalNormalCount(totalNormalCount);
            normalAndAbnormalCountDTO.setTotalAbnormalCount(totalAbnormalCount);
            return Result.ok(normalAndAbnormalCountDTO);
        } catch (Exception e){
            return Result.fail().message("查询失败！");
        }
    }

    /**
     * 查询所有任务详情列表
     * @return
     */
    @Override
    public Result selectAllTaskDetailList() {
        try {
            QueryWrapper<Experiment> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", 0)
                    .orderByDesc("create_time");
            List<Experiment> experimentList = experimentMapper.selectList(queryWrapper);
            if (experimentList == null) {
                return Result.fail().message("未查询到巡检记录");
            }
            List<TaskDetailDTO> experimentDetailList = new ArrayList<>();
            Integer totalCount = 0, totalNormalCount = 0, totalAbnormalCount = 0;
            for(Experiment experiment : experimentList){
                Integer taskCount = 5, normalTaskCount = 0, abnormalTaskCount = 0;
                List<Object> list = new ArrayList();
                Integer normalCount3 = experimentMapper.selectNormalCount(experiment.getExperimentId());
                experiment.setExperimentNormalNum(normalCount3);
                experiment.setExperimentExceptionNum(6 - normalCount3);
                if(normalCount3 == 6){
                    experiment.setExperimentIsNormal(1);
                    normalTaskCount++;
                }else {
                    experiment.setExperimentId(0);
                    abnormalTaskCount++;
                }
                String url = experiment.getPhotoUrl();
                if(url != null && !url.isEmpty()){
                    String photoUrl = FILE_URL + url;
                    experiment.setPhotoUrl(photoUrl);
                }
                list.add(experiment);
                QueryWrapper<Network> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("is_delete", 0)
                        .eq("network_id", experiment.getPreviousTaskId());
                Network network = networkMapper.selectOne(queryWrapper1);
                Integer normalCount2 = networkMapper.selectNormalCount(network.getNetworkId());
                network.setNetworkNormalNum(normalCount2);
                network.setNetworkExceptionNum(5 - normalCount2);
                if(normalCount2 == 5){
                    network.setNetworkIsNormal(1);
                    normalTaskCount++;
                }else {
                    network.setNetworkId(0);
                    abnormalTaskCount++;
                }
                String url1 = network.getPhotoUrl();
                if(url1 != null && !url1.isEmpty()){
                    String photoUrl = FILE_URL + url1;
                    network.setPhotoUrl(photoUrl);
                }
                list.add(network);
                QueryWrapper<Host> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("is_delete", 0)
                        .eq("host_id", network.getPreviousTaskId());
                Host host = hostMapper.selectOne(queryWrapper2);
                Integer normalCount1 = hostMapper.selectNormalCount(host.getHostId());
                host.setHostNormalNum(normalCount1);
                host.setHostExceptionNum(5 - normalCount1);
                if(normalCount1 == 5){
                    host.setHostIsNormal(1);
                    normalTaskCount++;
                }else {
                    host.setHostId(0);
                    abnormalTaskCount++;
                }
                String url2 = host.getPhotoUrl();
                if(url2 != null && !url2.isEmpty()){
                    String photoUrl = FILE_URL + url2;
                    host.setPhotoUrl(photoUrl);
                }
                list.add(host);
                QueryWrapper<Electric> queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.eq("is_delete", 0)
                        .eq("electric_id", host.getPreviousTaskId());
                Electric electric = electricMapper.selectOne(queryWrapper3);
                Integer normalCount = electricMapper.selectNormalCount(electric.getElectricId());
                electric.setElectricNormalNum(normalCount);
                electric.setElectricExceptionNum(4 - normalCount);
                if(normalCount == 4){
                    electric.setElectricIsNormal(1);
                    normalTaskCount++;
                }else {
                    electric.setElectricId(0);
                    abnormalTaskCount++;
                }
                String url3 = host.getPhotoUrl();
                if(url3 != null && !url3.isEmpty()){
                    String photoUrl = FILE_URL + url3;
                    electric.setPhotoUrl(photoUrl);
                }
                list.add(electric);
                QueryWrapper<Cabinet> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.eq("is_delete", 0)
                        .eq("cabinet_id", electric.getPreviousTaskId());
                Cabinet cabinet = cabinetMapper.selectOne(queryWrapper4);
                Integer cabinetNormalNum = cabinetMapper.selectNormalCount(cabinet.getCabinetId());
                cabinet.setCabinetNormalNum(cabinetNormalNum);
                cabinet.setCabinetExceptionNum(6 - cabinetNormalNum);
                if (cabinetNormalNum == 6){
                    cabinet.setCabinetIsNormal(1);
                    normalTaskCount++;
                }else {
                    cabinet.setCabinetId(0);
                    abnormalTaskCount++;
                }
                String url4 = cabinet.getPhotoUrl();
                if(url4 != null && !url4.isEmpty()){
                    String photoUrl = FILE_URL + url4;
                    cabinet.setPhotoUrl(photoUrl);
                }
                list.add(cabinet);
                Collections.reverse(list);
                TaskDetailDTO taskDetailDTO = new TaskDetailDTO();
                taskDetailDTO.setTaskDetailList(list);
                taskDetailDTO.setTaskCount(taskCount);
                taskDetailDTO.setNormalTaskCount(normalTaskCount);
                taskDetailDTO.setAbnormalTaskCount(abnormalTaskCount);
                User user = userMapper.selectById(cabinet.getUserId());
                taskDetailDTO.setUserName(user.getUserName());
                experimentDetailList.add(taskDetailDTO);
                totalCount++;
                if(abnormalTaskCount == 0){
                    totalNormalCount++;
                }else {
                    totalAbnormalCount++;
                }
            }
            InspectionRecordDTO inspectionRecordDTO = new InspectionRecordDTO();
            inspectionRecordDTO.setInspectionRecordList(experimentDetailList);
            inspectionRecordDTO.setTotalCount(totalCount);
            inspectionRecordDTO.setNormalCount(totalNormalCount);
            inspectionRecordDTO.setAbnormalCount(totalAbnormalCount);
            return Result.ok(inspectionRecordDTO);
        } catch (Exception e){
            return Result.fail().message("巡检任务查询失败！");
        }
    }

    /**
     * 管理员删除某次任务
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result deleteTask(Integer id) {
        try{
            Cabinet cabinet = cabinetMapper.selectById(id);
            if(cabinet != null){
                return Result.fail().message("任务不存在！");
            }
            cabinet.setIsDelete(1);
            cabinetMapper.updateById(cabinet);
            QueryWrapper<Electric> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("previous_task_id", cabinet.getCabinetId())
                    .eq("previous_task_type", 1)
                    .eq("is_delete", 0);
            Electric electric = electricMapper.selectOne(queryWrapper);
            electric.setIsDelete(1);
            electricMapper.updateById(electric);
            QueryWrapper<Host> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("previous_task_id", electric.getElectricId())
                    .eq("previous_task_type", 2)
                    .eq("is_delete", 0);
            Host host = hostMapper.selectOne(queryWrapper1);
            host.setIsDelete(1);
            hostMapper.updateById(host);
            QueryWrapper<Network> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("previous_task_id", host.getHostId())
                    .eq("previous_task_type", 3)
                    .eq("is_delete", 0);
            Network network = networkMapper.selectOne(queryWrapper2);
            network.setIsDelete(1);
            networkMapper.updateById(network);
            QueryWrapper<Experiment> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("previous_task_id", network.getNetworkId())
                    .eq("previous_task_type", 4)
                    .eq("is_delete", 0);
            Experiment experiment = experimentMapper.selectOne(queryWrapper3);
            experiment.setIsDelete(1);
            experimentMapper.updateById(experiment);
            return Result.ok().message("删除成功");
        } catch (Exception e){
            return Result.fail().message("删除失败！");
        }
    }

    /**
     * 管理员查询各机柜检修正常数
     * @return
     */
    @Override
    public Result selectAllTaskNormalCount() {
        TaskNormalCountDTO taskNormalCountDTO = new TaskNormalCountDTO();
        try{
            Integer cabinetNormalCount = cabinetMapper.selectNormalTotalCount();
            Integer electricNormalCount = electricMapper.selectNormalTotalCount();
            Integer hostNormalCount = hostMapper.selectNormalTotalCount();
            Integer networkNormalCount = networkMapper.selectNormalTotalCount();
            Integer experimentNormalCount = experimentMapper.selectNormalTotalCount();
            taskNormalCountDTO.setCabinetNormalCount(cabinetNormalCount);
            taskNormalCountDTO.setElectricNormalCount(electricNormalCount);
            taskNormalCountDTO.setHostNormalCount(hostNormalCount);
            taskNormalCountDTO.setNetworkNormalCount(networkNormalCount);
            taskNormalCountDTO.setExperimentNormalCount(experimentNormalCount);
            return Result.ok(taskNormalCountDTO);
        } catch (Exception e){
            return Result.fail().message("查询失败！");
        }
    }

    /**
     * 管理员查询各机柜检修异常数
     * @return
     */
    @Override
    public Result selectAllTaskAbnormalCount() {
        TaskAbnormalCountDTO taskAbnormalCountDTO = new TaskAbnormalCountDTO();
        try{
            Integer cabinetAbnormalCount = cabinetMapper.selectAbnormalTotalCount();
            Integer electricAbnormalCount = electricMapper.selectAbnormalTotalCount();
            Integer hostAbnormalCount = hostMapper.selectAbnormalTotalCount();
            Integer networkAbnormalCount = networkMapper.selectAbnormalTotalCount();
            Integer experimentAbnormalCount = experimentMapper.selectAbnormalTotalCount();
            taskAbnormalCountDTO.setCabinetAbnormalCount(cabinetAbnormalCount);
            taskAbnormalCountDTO.setElectricAbnormalCount(electricAbnormalCount);
            taskAbnormalCountDTO.setHostAbnormalCount(hostAbnormalCount);
            taskAbnormalCountDTO.setNetworkAbnormalCount(networkAbnormalCount);
            taskAbnormalCountDTO.setExperimentAbnormalCount(experimentAbnormalCount);
            return Result.ok(taskAbnormalCountDTO);
        } catch (Exception e) {
            return Result.fail().message("查询失败！");
        }
    }


//
//    public Result selectTaskList(){
//        UserDTO user = UserHolder.getUser();
//        Integer userId = user.getId();
//        QueryWrapper<Cabinet> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("user_id", userId)
//                .eq("is_delete", 0)
//                .eq("previous_task_id", 0);
//        List<Cabinet> cabinets = cabinetMapper.selectList(queryWrapper);
//        List<TaskDTO> taskDTOList = new ArrayList<>();
//        TaskDTO taskDTO = new TaskDTO();
//        if(cabinets != null || !cabinets.isEmpty()){
//            cabinets.forEach(cabinet -> {
//                taskDTO.setTaskType(cabinet.getTaskType());
//                taskDTO.setTaskId(cabinet.getCabinetId());
//                taskDTOList.add(taskDTO);
//            });
//        }
//        QueryWrapper<Electric> queryWrapper1 = new QueryWrapper<>();
//        queryWrapper1.eq("user_id", userId)
//                .eq("is_delete", 0)
//                .eq("previous_task_id", 0);
//        List<Electric> electrics = electricMapper.selectList(queryWrapper1);
//        if(electrics != null || !electrics.isEmpty()){
//            electrics.forEach(electric -> {
//                taskDTO.setTaskType(electric.getTaskType());
//                taskDTO.setTaskId(electric.getElectricId());
//                taskDTOList.add(taskDTO);
//            });
//        }
//        QueryWrapper<Host> queryWrapper2 = new QueryWrapper<>();
//        queryWrapper2.eq("user_id", userId)
//                .eq("is_delete", 0)
//                .eq("previous_task_id", 0);
//        List<Host> hosts = hostMapper.selectList(queryWrapper2);
//        if(hosts != null || !hosts.isEmpty()){
//            hosts.forEach(host -> {
//                taskDTO.setTaskType(host.getTaskType());
//                taskDTO.setTaskId(host.getHostId());
//                taskDTOList.add(taskDTO);
//            });
//        }
//        QueryWrapper<Network> queryWrapper3 = new QueryWrapper<>();
//        queryWrapper3.eq("user_id", userId)
//                .eq("is_delete", 0)
//                .eq("previous_task_id", 0);
//
//    }
}
